﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace EasyUIMvc
{
    public class ScriptBuilder
    {
        private static ScriptBuilder ScriptManagerInstance { get; set; }
        private IDictionary<string, string> Scripts { get; set; }

        private ScriptBuilder()
        {
            Scripts = new Dictionary<string, string>();
        }

        public static ScriptBuilder Instance()
        {
            return ScriptManagerInstance ?? (ScriptManagerInstance = new ScriptBuilder());
        }

        public ScriptBuilder AddScript(string script)
        {
            Scripts.Add(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture), script);
            return this;
        }

        public ScriptBuilder AddScript(string name, string script)
        {
            if (Scripts.ContainsKey(name) == false)
            {
                Scripts.Add(name, script);
            }
            else
            {
                Scripts[name] = script;
            }
            return this;
        }

        public string GetScripts()
        {
            var sb = new StringBuilder();
            sb.AppendLine("<script type='text/javascript'>");
            sb.AppendLine("  jQuery(document).ready(function () {");
            foreach (string key in Scripts.Keys)
            {
                sb.AppendLine("    " + Scripts[key]);
            }
            sb.AppendLine("  });");
            sb.AppendLine("</script>");

            Scripts.Clear();

            return sb.ToString();
        }
    }
}
